package org.e_gold.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.e_gold.dao.EventDAO;
import org.e_gold.model.Event;
import org.e_gold.model.crawler.livescore.CEvent;
import org.e_gold.service.AIService;
import org.e_gold.service.CEventService;
import org.e_gold.service.EventService;
import org.e_gold.util.Bet365;
import org.e_gold.util.CalcUtil;
import org.e_gold.util.StringUtil;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EventServiceImpl implements EventService, Bet365 {

	private static final Logger logger = Logger.getLogger(EventServiceImpl.class);

	@Autowired
	private EventDAO eventDAO;

	@Autowired
	private AIService aiService;

	@Autowired
	private CEventService cEventService;

	@Override
	// production - backup
	public List<Event> exposeAllEvent(Elements eEvents) {

		List<Event> events = new ArrayList<Event>();
		for (int i = 1; i <= (eEvents.size() - 3); i++) {
			Element e = eEvents.get(i - 1);
			try {
				Event event = new Event();
				String eventName = StringUtil.getName(e.text());
				event.setName(eventName);
				//home & away team parsing
				if(!eventName.contains(" v ")){
					continue;
				}
				event.setHomeName(eventName.split(" v ")[0]);
				event.setAwayName(eventName.split(" v ")[1]);

				//goal info
				Elements scoreInfo = e.select(".Score");
				if(scoreInfo.size() > 0){
					String strScoreInfo = scoreInfo.get(0).text();
					if(!strScoreInfo.contains("-")){
						event.setTotalGoal(0);
					}else{
						event.setTotalGoal(CalcUtil.getTotalGoal(strScoreInfo));
					}
				}
				event.setLocation(e.select("a").attr("href"));

				//playTime
				Elements timeInfo = e.select("#ct" + i);
				if(timeInfo.size() > 0){
					event.setPlayTime(CalcUtil.getCurrentTime(timeInfo.get(0).text()));
				}else{
					event.setPlayTime(-1);
				}
				event.setLocationFull(BASE_SPORT + e.select("a").attr("href").substring(3));
				logger.info(":::::::::::::::");
				logger.info("Event name : " + StringUtil.getName(e.text()));
				logger.info(e.select(".Score").text());
				logger.info(event.getPlayTime());
				if (aiService.filterEvent(event)) {
					logger.info("filtered added: " + StringUtil.getName(e.text()));
					events.add(event);
				}else{
					logger.info("filtered removed: " + StringUtil.getName(e.text()));
				}
			} catch (Exception ex) {
				logger.error(" exposeAllEvent  Parse error : " + e.text());
				logger.error(ex);
				ex.printStackTrace();
			}
		}
		return filterEventByCondition(events);
	}

	private List<Event> filterEventByCondition(List<Event> lstEvent){
		List<Event> events = new ArrayList<Event>();
		for(Event event : lstEvent){
			try{
				CEvent cevent = cEventService.getEventByHomeAndAwayName(event.getHomeName(), event.getAwayName());
				if(cevent != null){
					if(cevent.getLeague().isStatus()){
						event.setLeague(cevent.getLeague());
						events.add(event);
						logger.info("filterEventByCondition added: " + event.getName() + " || because: " + cevent.getLeague().getName());
					}else{
						logger.info("filterEventByCondition denied: " + event.getName() +" || because: " + cevent.getLeague().getName());
					}
				}
			}catch(Exception ex){
				logger.error("filterEventByCondition exception: " + event.getName());
				logger.error(ex);
			}
		}
		return events;
	}

	@Override
	public List<Event> persistEvent(List<Event> events) {

		List<Event> savedEvent = new ArrayList<Event>();
		for (Event event : events) {
			// insert new or populate old event: this is good solution :D ^____^
			Event eventPersisted = eventDAO.findByName(event.getName());

			if (eventPersisted == null) {
				eventPersisted = eventDAO.insert(event);
			}
			//try to find country & league
			CEvent cevent = cEventService.getEventByHomeAndAwayName(event.getHomeName(), event.getAwayName());
			if(cevent != null){
				eventPersisted.setLeague(cevent.getLeague());
			}
			eventPersisted.setTotalGoal(event.getTotalGoal());
			eventPersisted.setPlayTime(event.getPlayTime());
			eventDAO.update(eventPersisted);
			savedEvent.add(eventPersisted);
		}
		return savedEvent;
	}
}
